#include "Mutex.h"
#include "stdafx.h"

namespace syncLib
{

    Mutex::Mutex(BOOL bInitialOwner)
    {
        mHandle_.Attach(CreateMutex(NULL, bInitialOwner, NULL));

        if(!mHandle_)
        {
            throw std::runtime_error("Error mutex initialization");
        }
    }

    Mutex::Mutex(BOOL bInitialOwner, LPCTSTR lpName)
    {
        mHandle_.Attach(CreateMutex(NULL, bInitialOwner, lpName));

        if(!mHandle_)
        {
            throw std::runtime_error("Error mutex initialization");
        }

    }

    Mutex::Mutex(LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner, LPCTSTR lpName)
    {
        mHandle_.Attach(CreateMutex(lpMutexAttributes, bInitialOwner, lpName));

        if(!mHandle_)
        {
            throw std::runtime_error("Error mutex initialization");
        }

    }

    void Mutex::Lock()
    {
        assert(mHandle_);

        switch (WaitForSingleObject(mHandle_, INFINITE))
        {
        case WAIT_OBJECT_0:
            break;
        case WAIT_ABANDONED:
        case WAIT_TIMEOUT:
        case WAIT_FAILED:
            assert(false);
            break;

        default:
            throw std::runtime_error("Mutex. WaitForSingleObject fails");
            break;
        }
    }

    void Mutex::UnLock()
    {
        assert(mHandle_);

        ReleaseMutex(mHandle_);
    }

};